#!/usr/bin/env python3
# -*- coding:utf-8 -*-

import os
import re

import logging
from ctools.logext import *

_rlog, _plog, _mlog, _tlog = get_loggers(__file__, __name__, propagate=False)

class iFilter(object):
    def __init__(self):
        self._ignore_patterns = []
        self._filter_patterns = []

    def patterns_iter(self, is_ignore=False):
        patterns = self._ignore_patterns if is_ignore else self._filter_patterns
        for p in patterns:
            yield p.pattern

    def add_pattern(self, pattern, is_ignore=False):
        patterns = self._ignore_patterns if is_ignore else self._filter_patterns
        for p in (p.pattern for p in patterns):
            if p == pattern:    # already exists
                return False
        patterns.append(re.compile(pattern))
        return True

    def del_pattern(self, pattern, is_ignore=False):
        patterns = self._ignore_patterns if is_ignore else self._filter_patterns
        for p in patterns:
            if p.pattern == pattern:
                patterns.remove(p)
                return True
        return False

    def filter_item(self, name, default=True):
        if default:
            for pattern in self._ignore_patterns:
                if pattern.match(name):
                    return False
        else:
            for pattern in self._filter_patterns:
                if pattern.match(name):
                    return True
        return default

    def loadtxt(self, filename, is_ignore=False):
        with open(filename, 'r') as fd:
            for line in fd:
                line = line.strip()
                if not line or line.startswith('#'):
                    continue
                if is_ignore:
                    self._ignore_patterns.append(re.compile(line))
                else:
                    self._filter_patterns.append(re.compile(line))[1:]
